package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Messages;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.*;

@Service(version = "1.0.0")
public class MessagesApiImpl implements MessagesApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Override
    public boolean saveMessages(Long userId) {
        //通过userId查询他参与评论,点赞,喜欢的动态,进行分页,从quanzi_comment表中查
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);
        if (CollectionUtils.isEmpty(commentList)) {
            return false;
        }
        List<ObjectId> publishIds = new ArrayList<>();
        for (Comment comment : commentList) {
            publishIds.add(comment.getPublishId());
        }

        //获取所有动态信息
        List<Publish> publishList = this.mongoTemplate.find(Query.query(Criteria.where("id").in(publishIds)), Publish.class);

        List<Messages> messagesList = new ArrayList<>();

        for (Publish publish : publishList) {
            //通过publishIds查询该动态所有评论的数量
            //查询   评论类型，1-点赞，2-评论
            Long likeCount = this.quanZiApi.queryCommentCount(publish.getId().toString(), 1);
            Long commentCount = this.quanZiApi.queryCommentCount(publish.getId().toString(), 2);

            Messages messages = new Messages();
            messages.setId(ObjectId.get());
            messages.setPublishId(publish.getId());
            messages.setUserId(publish.getUserId());
            messages.setLikeCount(Integer.valueOf(likeCount.toString()));
            messages.setCommentCount(Integer.valueOf(commentCount.toString()));
            messages.setMedias(publish.getMedias());
            messages.setText(publish.getText());
            messages.setReportCount(500);
            messages.setForwardingCount(1000);
            messages.setCreateDate(publish.getCreated());
            messages.setState(1);
            messages.setTopState(1);

            messagesList.add(messages);
        }
        return true;
    }

    /*
    查询用户参与的动态列表
     */
    @Override
    public PageInfo<Messages> queryMessagesList(String userId, Integer page, Integer pageSize,
                                                String sortProp, String sortOrder) {

        //通过userId查询他参与评论,点赞,喜欢的动态,进行分页,从quanzi_comment表中查
        List<Comment> commentList = this.mongoTemplate.find(Query.query(Criteria.where("userId").is(Long.valueOf(userId))), Comment.class);
        if (CollectionUtils.isEmpty(commentList)) {
            return null;
        }

        //去重,防止用户同时评论,点赞
        Set<ObjectId> publishIds = new HashSet<>();
        for (Comment comment : commentList) {
            publishIds.add(comment.getPublishId());
        }
        //获取所有publishIds,根据条件查询动态信息
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(
                "descending".equals(sortOrder) ? Sort.Order.desc(sortProp) : Sort.Order.asc(sortProp)));
        Query query = new Query(Criteria.where("publishId").in(publishIds)).with(pageRequest);
        List<Messages> messagesList = this.mongoTemplate.find(query, Messages.class);

        PageInfo<Messages> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(messagesList);
        pageInfo.setTotal(publishIds.size());

        return pageInfo;
    }

    @Override
    public Messages queryMessagesById(String publishId) {
        //根据消息id查询消息表
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)));
        Messages messages = this.mongoTemplate.findOne(query, Messages.class);
        if (null != messages) {
            return messages;
        }
        return null;
    }

    @Override
    public boolean updateTopStateById(String messagesId, String top) {
        Query query = Query.query(Criteria.where("_id").is(messagesId));
        Update update = Update.update("topState", top == "top" ? 2 : 1);
        UpdateResult updateResult = this.mongoTemplate.updateFirst(query, update, Messages.class);
        if (updateResult.getModifiedCount() == 0) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean updateMessage(Messages messages) {
        try {
            Query query = new Query();
            query.addCriteria(Criteria.where("publishId").is(messages.getPublishId()));
            Update update = new Update();
            update.set("state", messages.getState());
            mongoTemplate.upsert(query,update,Messages.class);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
